import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {httpService} from "../../service/httpService";
import {Storage} from '@ionic/storage';
import {HOST_URL} from "../../service/Constants";
import {ChatView} from '../news/chat-view/chat-view';

@Component({
  selector: 'page-contact',
  templateUrl: 'contact.html'
})
export class Contact {
  contactList;
  user;
  userCode;
  token;
  constructor(public navCtrl: NavController,
              private http: httpService,
              public storage: Storage,) {
    this.storage.get("userInfo").then(data => {
      this.user = data;
    });
    this.storage.get("token").then(data => {
      this.token = data;
      //加载联系人列表
      this.http.get(HOST_URL + '/api/v1/user/?filter=', {}, this.token).then(res => {
        if (res.error.code == '0') {
          this.contactList = res.rows;
        } else if (res.error.code == '801') {
        }
      })
    });

  }

//跳转聊天页面
  goChatView(item) {
      //判断是否在聊天列表里面
      this.http.get(HOST_URL + '/api/v1/chat_list/?filter=', {
        idUser: this.user.id,
        idTargetUser: item.id,
        listType: '1'
      },this.token).then(res => {
        if (res.error.code == '0') {
          if(res.rows.length==0){//不在
            this.addtoChatList(item)
          }else{
            this.navCtrl.push(ChatView, {item: item});
          }

        } else if (res.error.code == '801') {

        }
      })
  }
  //添加到聊天列表
  addtoChatList(targetUser){
    //添加到聊天列表
    this.http.postBody(HOST_URL + '/api/v1/chat_list',
      [{
        idUser: this.user.id,
        idTargetUser: targetUser.id,
        listType: '1',
        listState: '1', //显示
        unreadNum: 0
      },
        {
          idUser: targetUser.id,
          idTargetUser: this.user.id,
          listType: '1',
          listState: '0', //隐藏
          unreadNum: 0
        }
      ],this.token).then(res => {
      if (res.error.code == '0') {
        this.navCtrl.push(ChatView, {item: targetUser});
      } else if (res.error.code == '801') {

      }
    })
  }
}
